<template>
	<cl-crud ref="crud" @load="onLoad" :on-refresh="onRefresh">
		<cl-data-table
			id="shopDay2Info"
			v-bind="table"
			:data="list"
			:loading="loading"
			auto-page
			full
		>
			<template #head>
				<el-row type="flex">
					<cl-filter-group v-model="search" @reset="changeBiz">
						<cl-filter label="事业部">
							<cl-select
								v-model="search.biz_id"
								placeholder="请选择"
								style="width: 150px"
								filterable
								@change="changeBiz"
							>
								<el-option
									v-for="item in business"
									:key="item.biz_id"
									:label="item.biz_name"
									:value="item.biz_id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="分公司">
							<cl-select
								v-model="search.company_id"
								placeholder="请选择"
								filterable
								style="width: 150px"
								clearable
							>
								<el-option label="全部" value="" />

								<el-option
									v-for="item in bizRefData.company"
									:key="item.company_id"
									:label="item.company_name"
									:value="item.company_id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="品牌">
							<cl-select
								v-model="search.bra_id"
								placeholder="全部"
								filterable
								style="width: 150px"
								clearable
								multiple
								collapse-tags
							>
								<el-option
									v-for="item in bizRefData.brand"
									:key="item.bra_id"
									:label="item.bra_name"
									:value="item.bra_id"
								/>
							</cl-select>
						</cl-filter>
						<cl-filter label="所属门店">
							<cl-shop-select
								v-model="search.dept_id"
								placeholder="请选择"
								filterable
								clearable
								style="width: 150px"
								@change="changeDept"
								show-all
								:biz_id="search.biz_id"
							/>
						</cl-filter>
						<cl-filter label="门店老师">
							<teacherSelect ref="teacherSelect" v-model="search.teacher_id" />
						</cl-filter>
						<cl-filter label="客户类型">
							<cl-select v-model="search.cus_type" @change="refresh" clearable>
								<el-option value="" label="全部" />
								<el-option :value="1" label="新客" />
								<el-option :value="2" label="老客" />
								<el-option :value="3" label="老转新" />
							</cl-select>
						</cl-filter>
						<cl-filter label="消费时间">
							<cl-date-picker
								v-model="search.date"
								type="daterange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="yyyy-MM-dd"
								style="width: 210px"
								:clearable="false"
								:picker-options="pickerOptions"
							/>
						</cl-filter>
					</cl-filter-group>
					<cl-flex1 />
					<cl-table-handle
						:print="printParams"
						:columns="initColumns"
						v-model="table.columns"
						is-async-show
						:downQuery="search"
						:excelDownQuery="excelDownQuery"
						@export-file="exportFile"
						@confirm="filterConfirm"
					/>
				</el-row>
			</template>
			<cl-empty slot="empty" />

			<template #column-opt="{ scope: { row } }">
				<el-button
					type="primary"
					v-auth="'store_cusdetailindex_look'"
					@click.stop="openDetail(row)"
				>
					详情
				</el-button>
			</template>
		</cl-data-table>
	</cl-crud>
</template>

<script>
import { exportExcelCoustom } from "@/utils/excel";
import { cloneDeep } from "cl-admin/utils";
import { flatten } from "@/utils";
import dayjs from "dayjs";
import teacherSelect from "@/components/teacher-select";
const pageTitle = "店-日详情2"

export default {
	inject: ["$layout"],
	components: {
		teacherSelect
	},
	data() {
		return {
			printParams: {
				id: "shopDay2Info",
				popTitle: pageTitle
			},
			excelDownQuery: {
				name: pageTitle,
				method: "get",
				url: "/finance/storedaydetail"
			},
			search: {
				biz_id: "",
				company_id: "",
				bra_id: [],
				dept_id: "",
				cus_type: "",
				teacher_id: "",
				date: [
					dayjs()
						// .startOf("day")
						.format("YYYY-MM-DD"),
					dayjs()
						// .endOf("day")
						.format("YYYY-MM-DD")
				]
			},
			companyList: [],
			brandList: [],
			shopList: [],
			table: {
				"context-menu": ["refresh"],
				columns: [],
				showSummary: true,
				summaryMethod: () => {
					return this.summariesArr;
				},
				showPage: true,
				autoPage: true,
				limit: 20
			},
			summariesArr: [],
			list: [],
			initColumns: [],
			loading: false,
			pickerOptions: {
				onPick: ({ maxDate, minDate }) => {
					this.selectDate = minDate.getTime();
					if (maxDate) {
						this.selectDate = "";
					}
				},
				disabledDate: time => {
					if (this.selectDate !== "") {
						const one = 30 * 24 * 3600 * 1000;
						const minTime = this.selectDate - one;
						const maxTime = this.selectDate + one;
						return time.getTime() < minTime || time.getTime() > maxTime;
					}
				}
			},
			selectDate: ""
		};
	},
	computed: {
		bizRefData() {
			let { biz_id } = this.search;
			return this.getBizRefData(biz_id);
		}
	},
	created() {
		this.search.biz_id = this.getCurrBiz();
		this.init();
	},
	methods: {
		async init() {
			const { biz_id } = this.search;
			this.getBizRefBrand(biz_id);
			this.getBizRefCompany(biz_id);
			this.getBizRefShop(biz_id);
			this.initData();
		},
		async initData() {
			this.getTeacherList();
		},
		onLoad({ ctx, app }) {
			ctx.service(this.$service.finance)
				.set("dict", {
					api: { page: "storedaydetail" }
				})
				.done();
			// app.refresh(this.search);
		},
		async onRefresh(params, { next, render }) {
			this.loading = true;
			const { data_list, title_list } = await next(params).finally(() => {
				this.loading = false;
			});
			this.list = data_list;
			let noSum = ["date", "cus_name", "biz_name", "company_name", "bra_name"];
			function filterArr(arr) {
				// console.log(arr);
				arr.forEach(v => {
					v.label = v.name;
					v.prop = v.key;
					v.minWidth = 120;
					if (noSum.includes(v.key)) {
						v.fixed = true;
					}
					if ("children" in v && v.children.length) {
						filterArr(v.children);
					}
				});
				return arr;
			}
			this.initColumns = filterArr(title_list);
			this.initColumns.push({
				label: "操作",
				prop: "opt",
				width: 80,
				disable: true,
				fixed: "right"
			});

			const allColumns = flatten(this.initColumns);
			this.getSummaries({ columns: allColumns });

			this.table.columns = cloneDeep(this.initColumns);
			render(data_list);
		},
		// crud刷新
		refresh() {
			this.$refs.crud.refresh({ page: 1, ...this.search });
		},
		onResize(h) {
			this.table.maxHeight = h;
		},
		// 表格合计
		getSummaries({ columns, data }) {
			let ignore = [
				"cus_name",
				"biz_name",
				"company_name",
				"adviser_teachers",
				"cus_id",
				"dept_name",
				"is_rest_dec",
				"teachers",
				"cus_type_dec",
				"projects",
				"tname",
				"sell_teachers",
				"maintain_date",
				"maintain_price",
				"out_trade_no",
				"final_sell_teachers",
				"light_teachers",
				"lightadviser_teachers",
				"order_no"
			];
			const newArr = columns.map((column, index) => {
				if (index === 0) {
					return "合计";
				}
				let prop = column.prop;
				if (ignore.includes(prop)) return "";
				const values = this.list.map(item => Number(item[prop]));
				if (values.every(value => isNaN(value))) {
					return "";
				}
				let sum = values.reduce((prev, curr) => {
					const value = Number(curr);
					if (!isNaN(value)) {
						return prev + curr;
					}
					return prev;
				}, 0);
				return this.toFixed(sum);
			});

			this.summariesArr = newArr;
			return newArr;
		},

		//切换事业部
		changeBiz() {
			this.search = {
				...this.search,
				company_id: "",
				bra_id: [],
				dept_id: "",
				teacher_id: ""
			};
			this.init();
		},
		// 切换门店
		changeDept() {
			this.search.teacher_id = "";
			this.getTeacherList();
			// this.refresh();
		},
		// 分公司
		async getCompanys() {
			const { biz_id } = this.search;
			this.companyList = [];
			if (!biz_id) return;
			const data = await this.$service.company.list({
				biz_id
			});
			this.companyList = data;
		},
		// 品牌
		async getBrands() {
			const { biz_id } = this.search;
			this.brandList = [];
			if (!biz_id) return;
			const data = await this.$service.brand.usermanage({
				biz_id
			});
			this.brandList = data;
		},
		// 门店
		async getShopList() {
			const { biz_id } = this.search;
			this.shopList = [];
			if (!biz_id) return;
			const data = await this.$service.shop.list({ biz_id });
			this.shopList = data.reduce((prev, curr) => [...prev, ...curr.children], []);
		},
		// 老师列表
		async getTeacherList() {
			const { biz_id, dept_id } = this.search;
			if (!biz_id) return;

			this.$nextTick(() => {
				this.$refs.teacherSelect.init({
					dept_id,
					biz_id,
					status: 1,
					is_teacher: 1
				});
			});
		},
		// 详情
		openDetail(row) {
			this.$layout.openCusDetail(row, "order");
		},
		// 导出EXCEl
		exportFile() {
			exportExcelCoustom("店-日详情2", this.list, this.table.columns, this.summariesArr);
			// exportExcel("#shopDay2Info");
		},
		// 表头筛选
		filterConfirm(columns) {
			const allColumns = flatten(columns);
			this.getSummaries({ columns: allColumns });
		}
	}
};
</script>

<style lang="scss" scoped>
::v-deep {
	.el-table--scrollable-x {
		.el-table__body-wrapper {
			z-index: 2;
		}
	}
}
</style>
